package com.hx.vending.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.hx.vending.annotation.Authorization;
import com.hx.vending.annotation.CurrentUserId;
import com.hx.vending.bean.*;
import com.hx.vending.bean.config.AlipayConfig;
import com.hx.vending.service.*;
import com.hx.vending.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2018/12/21.
 */
@Controller
@RequestMapping("/alipay")
public class AliPayController {
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private IOnlineOrderService onlineOrderService;
    @Autowired
    private IEquipmentService equipmentService;
    @Autowired
    private IRefundService refundService;

    /**
     * 下单支付
     * @param customerId 买家id
     * @param onlineOrderId 订单id
     * @return
     */
    @ResponseBody
    @RequestMapping("/orderPayment")
    public Msg test(Integer customerId,Integer onlineOrderId){
        Object orderStr = customerService.alipaypayment(customerId,onlineOrderId);
        return Msg.success().add("msg",orderStr);
    }

    /*
    * 支付回调
    * */
    @RequestMapping (value = "/alipayCallBack",method = RequestMethod.POST)
    @ResponseBody
    public String aliPayCallBack(HttpServletRequest request){
        try {
             String str = this.customerService.notify(request);
             System.out.println("支付宝支付返回结果==================="+str);
             return str;
        } catch (Exception e) {
            return "failure";
        }
    }

    @RequestMapping(value = "/refund",method = RequestMethod.POST)
    @ResponseBody
    public String refund(HttpServletRequest request){
        try {
            String str = this.customerService.notifyRefund(request);
            return str;
        } catch (Exception e) {
            return "failure";
        }
    }

    /**
     * 同步回调
     * @param request
     * @return
     */
    @RequestMapping(value = "/returnUrl",method = RequestMethod.GET)
    public ModelAndView returnUrl(HttpServletRequest request){
        return this.customerService.returnUrl(request);
    }

    /*
    * 支付宝授权登陆
    * */
    @RequestMapping(value = "/aliPayEmpower", method = RequestMethod.GET)
    public String aliPayEmpower(String onlineOrderId){
        System.out.println("支付宝授权登陆");
        //回调接口
        String redirect_uri = "http://star-hi.cn/vending/alipay/aliPayRedirect";
        //1.URL拼接与scope详解
        /*String url = String.format("https://openauth.alipay.com/oauth2/appToAppAuth.htm?app_id=%s&redirect_uri=%s",
                AlipayConfig.APPID,redirect_uri);*/
        String url = String.format("https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=%s&scope=%s&redirect_uri=%s&state=%s",
                AlipayConfig.APPID, "auth_user",redirect_uri,onlineOrderId);
        //2.发送请求
        return "redirect:" + url;
    }

    /**
     * 支付宝授权登录回调
     */
    @RequestMapping("/aliPayRedirect")
    public String aliPayRedirect(String auth_code,String  state) throws Exception {
        //保存玩家信息
        return this.aliPayExchangeRedirect(auth_code,state);

    }

    //支付宝授权登录回调
    public String aliPayExchangeRedirect(String auth_code,String  state){
        System.out.println("支付宝授权登陆回调");
        System.out.println("auth_code："+auth_code);
        System.out.println("onlineOrderId====="+state);
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        //实例化支付宝API对象
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AlipayConfig.APPID, AlipayConfig.APP_PRIVATE_KEY, "json", "UTF-8", AlipayConfig.ALIPAY_PUBLIC_KEY, "RSA2");
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        //交易令牌值
        request.setCode(auth_code);
        //固定值
        request.setGrantType("authorization_code");
        //token值
        String auth_token = "";

        AlipaySystemOauthTokenResponse oauthTokenResponse = null;
        String id = "";
        try{
            oauthTokenResponse = alipayClient.execute(request);
            System.out.println("access_token："+ oauthTokenResponse.getAccessToken());
            if (null != oauthTokenResponse.getAccessToken() && null != oauthTokenResponse.getRefreshToken()) {
                //获取token值
                auth_token = oauthTokenResponse.getAccessToken();
                //第四步：调用接口获取用户信息
                AlipayUserInfoShareRequest shareRequest = new AlipayUserInfoShareRequest();
                AlipayUserInfoShareResponse userinfoShareResponse = null;
                try {
                    userinfoShareResponse = alipayClient.execute(shareRequest, auth_token);
                } catch (AlipayApiException e) {
                    //处理异常
                    e.printStackTrace();
                }
                //用户支付宝id
                /*session.setAttribute("openid", userinfoShareResponse.getUserId());
                session.setAttribute("token", oauthTokenResponse.getAccessToken());
                session.setAttribute("headimgurl", userinfoShareResponse.getAvatar());
                session.setAttribute("nickname", userinfoShareResponse.getNickName());*/

                Customer customer = new Customer();

                //支付宝唯一id
                customer.setCustomerOpenId(userinfoShareResponse.getUserId());
                //昵称
                customer.setCustomerName(userinfoShareResponse.getNickName());
                //支付宝用户头像
                customer.setCustomerPhoto(userinfoShareResponse.getAvatar());
                //省份
                customer.setCustomerProvince(userinfoShareResponse.getProvince());
                //城市
                customer.setCustomerCity(userinfoShareResponse.getCity());
                customer.setCustomerType(2);
                //性别
                if (userinfoShareResponse.getGender().equals("M")) {
                    //M为男性
                    customer.setCustomerSex("1");
                } else if (userinfoShareResponse.getGender().equals("F")) {
                    //F未女性
                    customer.setCustomerSex("2");
                } else {
                    //0为未知
                    customer.setCustomerSex("0");
                }
                //存在则更新，不存在则保存
                customerService.saveOrUpdate(customer);
                Customer c = new Customer();
                c.setCustomerOpenId(userinfoShareResponse.getUserId());
                Customer cc = customerService.selectByPrimary(c);
                OnlineOrder oo = new OnlineOrder();
                oo.setOnlineOrderId(Integer.parseInt(state));
                OnlineOrder onlineOrder = onlineOrderService.selectByPrimaryKeySelective(oo);
                //设备
                Equipment e = new Equipment();
                e.setEquipmentId(onlineOrder.getOnlineOrderEquipmentId());
                Equipment equipment = equipmentService.selectByPrimary(e);
                if(ToolUtil.isNotEmpty(cc)){
                    CustomerRecharge cr1 = new CustomerRecharge();
                    cr1.setCustomerRechargeUserId(equipment.getEquipmentUserId());
                    cr1.setCustomerRechargeCustomerId(cc.getCustomerId());
                    CustomerRecharge cr = customerService.selectRechargeByPrimary(cr1);
                    if(ToolUtil.isEmpty(cr)){
                        CustomerRecharge customerRecharge = new CustomerRecharge();
                        customerRecharge.setCustomerRechargeUserId(equipment.getEquipmentUserId());
                        customerRecharge.setCustomerRechargeCustomerId(cc.getCustomerId());
                        id= cc.getCustomerId().toString();
                        customerService.insertCustomerRecharge(customerRecharge);
                        //实例化一个Cookie
                        Cookie cookie = new Cookie("customerId",cc.getCustomerId().toString());
                        //生存时间
                        cookie.setMaxAge(3600 * 24);
                        //设置cookie路径
                        cookie.setPath("/");
                        //写入肯定是要用response
                        response.addCookie(cookie);
                    }else{
                        id = cr.getCustomerRechargeCustomerId().toString();
                        //实例化一个Cookie
                        Cookie cookie = new Cookie("customerId",cr.getCustomerRechargeCustomerId().toString());
                        //生存时间
                        cookie.setMaxAge(3600 * 24);
                        //设置cookie路径
                        cookie.setPath("/");
                        //写入肯定是要用response
                        response.addCookie(cookie);
                    }
                }
            }else {
                System.out.println("---------------------交换令牌和刷新令牌获取为空,直接返回页面-----------------");
            }
        }catch(AlipayApiException e){
            System.out.println("捕捉到异常信息为:" + e.getMessage());
            System.out.println("错误码:" + e.getErrCode() + ",错误信息:" + e.getErrMsg());
            e.printStackTrace();
        }
        return "redirect:"+Constant.REDIRECTURL+"/"+state+"/"+id;
    }

    @RequestMapping("/test")
    @ResponseBody
    //@Authorization
    public Object pushTest(String count)throws Exception{
       /* Float float1 = 0.8F;//// 商户提现比例
        double double1 = Double.parseDouble(float1.toString());
        double pool = BigDecimalUtils.mul(12.4, double1 / 100);// 手续费

        pool = BigDecimalUtils.round(Math.ceil(pool*100), 100, 2);//手续费

        //实际到账金额
        Double subMoney = BigDecimalUtils.sub(12.4, pool);// 提现减去提现手续费
        return subMoney;*/
        /*String s = "869300038716258,0001,1,3,0001,1,3,0000,1,4,0000,1,4";
        String[] strs = s.split(",");
        RunnerShipment runnerShipment = new RunnerShipment();
        runnerShipment.stock(strs,1136);*/

        /*Timer timer = new Timer();
        timer.userIncomePush();*/
        String message = "充值订单:\n玩家ID:%s\n玩家昵称:%s\n充值金额:%s元\n充值时间:%s";
        Boolean b = PushUtils.getInstance().pushMessage(count, String.format(message,"1234","推送消息","2","2018-08-08 12:12:12"));
        return b;
        //String str = MD5.convertMD5("c56d0e9a7ccec67b4ea131655038d604");
        //return d;
        //System.out.println(PushUtils.getInstance().createMember("123456","userName","15800070014","2"));
    }

    /**
     * 退款
     * @param onlineOrderId 交易id
     * @param refund_amount 金额
     * @return
     */
    @RequestMapping("/aliPayRefund")
    @ResponseBody
    public Msg aliPayRefund(Integer onlineOrderId,Integer orderBuyId,Double refund_amount){
        return refundService.aliPayRefund(onlineOrderId,orderBuyId,refund_amount);
    }
    /**
     * 说明：单笔转账到支付宝账户
     * @param //out_biz_no  商户转账唯一订单号
     * @param //payee_type 收款方账户类型  (1、ALIPAY_USERID：支付宝账号对应的支付宝唯一用户号。以2088开头的16位纯数字组成。
     *                   2、ALIPAY_LOGONID：支付宝登录号，支持邮箱和手机号格式。)
     * @param //payee_account 收款方账户
     * @param amount 转账金额
     * @param //payer_show_name 付款方姓名
     *@param //payee_real_name 收款方真实姓名
     * @param //remark 转账备注
     */
    @RequestMapping("/withdraw")
    @ResponseBody
    @Authorization
    public Msg withdraw(Double amount,@CurrentUserId Integer userId,Integer type){
        return customerService.withdraw(amount,userId,type);
    }

    /**
     * 支付宝授权登陆(客户购买商品web)
     * @return
     */
    @RequestMapping("/alipayEmpowerWeb/{id}")
    public String aliPayEmpowerWeb(@PathVariable("id") String equipmentId){

        String redirect_uri = "http://star-hi.cn/vending/alipay/aliPayRedirectWeb";
        String url = String.format("https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=%s&scope=%s&redirect_uri=%s&state=%s",
                AlipayConfig.APPID, "auth_user",redirect_uri,equipmentId);
        return "redirect:" + url;
    }

    /**
     * 支付宝授权登录回调
     */
    @RequestMapping("/aliPayRedirectWeb")
    public String aliPayRedirectWeb(String auth_code,String  state) throws Exception {
        //保存玩家信息
        return customerService.aliPayExchangeRedirectWeb(auth_code,state);
    }

    private void smilePay(){
        //*/调用zolozGetMetaInfo完成设备信息采集
       /* Zoloz.zolozGetMetaInfo(mockInfo(), new ZolozCallback() {

            // 解析zolozGetMetaInfo返回的结果，如果成功，则请求商户服务端调用人脸初始化接口
            @Override
            public void response(Map smileToPayResponse) {
                if (smileToPayResponse != null) {
                    String code = (String) smileToPayResponse.get("code");
                    String metaInfo = (String) smileToPayResponse.get("metainfo");

                    if (code.equalsIgnoreCase("CODE_SUCCESS") && metaInfo != null) {
                        // 将metaInfo发送给商户服务端，由商户服务端发起刷脸初始化OpenAPI的调用
                    }
                }
            }
        });*/
    }

    /**
     * mock数据，真实商户请填写真实信息.
     */
    private Map mockInfo() {
        Map merchantInfo = new HashMap();
        //以下信息请根据真实情况填写
        //商户 Pid
        merchantInfo.put("merchantId", AlipayConfig.PARTNER);
        //ISV PID
        merchantInfo.put("partnerId", AlipayConfig.PARTNER);
        //添加刷脸付功能的appid
        merchantInfo.put("appId", AlipayConfig.APPID);
        //机具编号，便于关联商家管理的机具
        merchantInfo.put("deviceNum", "TEST_ZOLOZ_TEST");
        //商户的门店编号
        merchantInfo.put("storeCode", "TEST");
        //支付宝门店编号
        merchantInfo.put("alipayStoreCode", "TEST");

        return merchantInfo;
    }

}
